<template>
  <div class="login-container">
    <div class="login-container__form">
      <n-form ref="formRef" :show-label="false" :model="form" :rules="rules" size="large">
        <n-form-item path="mailbox">
          <n-input
            v-model:value="form.mailbox"
            :input-props="{ autocomplete: 'tel', name: 'mobile' }"
            placeholder="请输入邮箱号"
            @blur="removeSpaces"
          >
          </n-input>
        </n-form-item>
        <n-form-item path="password">
          <n-input
            v-model:value="form.password"
            :input-props="{
              autocomplete: 'current-password',
              name: 'password'
            }"
            clearable
            name="password"
            type="password"
            show-password-on="click"
            placeholder="请输入密码"
            @keyup.enter="handleSave"
          />
        </n-form-item>
      </n-form>

      <div class="form-foot">
        <n-button
          type="primary"
          size="large"
          :disabled="disabledLogin"
          :loading="loading"
          style="width: 100%"
          @click="handleSave"
        >
          登 录
        </n-button>
      </div>
    </div>
  </div>

  <x-verify ref="verifyRef" :v-space="15" @success="handleVerifySuccess" />
</template>

<script setup lang="ts">
  import md5 from 'js-md5'
  import { NForm, NFormItem, NInput, NButton, NCheckbox, NSpace, FormInst, useDialog, useMessage } from 'naive-ui'
  import { XVerify } from '@/components'
  import { useStore } from '@/store'
  import { useRouter } from 'vue-router'
  import { computed, reactive, ref } from 'vue'
  const dialog = useDialog()
  const store = useStore()
  const router = useRouter()
  const message = useMessage()
  const emits = defineEmits(['change-method'])
  const checkValue = ref(true)
  const loading = ref(false)
  const formRef = ref<FormInst | null>(null)
  const verifyRef = ref(null)
  const activeTab = ref('password')
  const tabs = ref([
    {
      name: '密码登录',
      type: 'password'
    },
    {
      name: '验证码登录',
      type: 'code'
    }
  ])
  const form = ref({
    mailbox: '',
    password: ''
  })
  const rules = reactive({
    mailbox: [
      {
        type: 'email',
        required: true,
        message: '请输入正确的邮箱号',
        trigger: ['blur', 'input']
      }
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
        trigger: ['blur', 'input']
      }
    ]
  })
  const disabledLogin = computed(() => {
    if (activeTab.value === 'password') {
      return !form.value.mailbox || !form.value.password || !checkValue.value
    } else {
      return !form.value.mailbox || !checkValue.value
    }
  })

  function removeSpaces() {
    form.value.mailbox = form.value.mailbox.replace(/\s+/g, '')
  }

  function handleSave() {
    formRef.value?.validate((errors) => {
      if (!errors) {
        if (activeTab.value === 'password') {
          verifyRef.value?.show()
        } else {
          _login()
        }
      } else {
        console.log(errors)
      }
    })
  }

  function _login(captchaVerification?: string) {
    loading.value = true
    store
      .dispatch('user/login', {
        errorMessageMode: 'none',
        mailbox: form.value.mailbox,
        password: md5(form.value.password),
        captchaVerification,
        loginType: activeTab.value === 'password' ? 1 : 2 // 登录类型：1-账密登陆；2-手机验证码登陆；3-微信扫码登陆；
      })
      .then(async () => {
        await store.dispatch('user/getUserInfo')
        generateUserRoutes()
        router.push({
          name: 'Advertising'
        })
      })
      .catch((res: any) => {
        if (res.code === '8031') {
          dialog.create({
            title: '提示',
            content: res.msg,
            positiveText: '找回密码',
            onPositiveClick: () => {
              handleFindPwd()
            }
          })
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  async function generateUserRoutes() {
    await store.dispatch('permission/generateUserRoutes')
  }

  function handleFindPwd() {
    router.push({
      name: 'SetPwd',
      query: {
        mobile: form.value.mailbox,
        type: 'forgot'
      }
    })
  }

  function handleVerifySuccess(res: any) {
    _login(res.captchaVerification)
  }
</script>

<style scoped lang="scss">
  .login-container {
    padding: 40px 56px 60px;

    &__header {
      display: flex;
      align-items: baseline;
      padding-bottom: 30px;
      font-size: 20px;
      color: #969799;

      span {
        cursor: pointer;
        vertical-align: baseline;
        &:first-child {
          margin-right: 24px;
        }
      }
      .bold {
        font-weight: 500;
        font-size: 26px;
        color: #323233;
        cursor: default;
      }
    }

    &__logo {
      display: flex;
      justify-content: center;
      padding-bottom: 20px;
      img {
        width: 200px;
      }
    }

    &__form {
      .form-foot {
        padding-top: 20px;

        .btn-forgot {
          text-align: right;
          margin-bottom: 16px;
        }
      }
    }

    &__footer {
      padding-top: 30px;
      text-align: center;
    }
  }
  .switch-type {
    position: absolute;
    display: flex;
    justify-content: space-between;
    align-items: center;
    right: 0;
    top: 0;
    height: 80px;

    > img {
      width: 80px;
      height: 80px;
      cursor: pointer;
    }

    &__tip {
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: -48px;
      right: 0;
      width: 139px;
      height: 32px;
      font-size: 14px;
      border-radius: 2px;
      color: #fff;
      background: #1b59d1;
      cursor: pointer;

      &:after {
        content: '';
        position: absolute;
        bottom: -4px;
        right: 15px;
        transform: translateX(-50%) rotate(45deg);
        border: 1px solid #155bd4;
        background: #155bd4;
        width: 7.8px;
        height: 7.8px;
        border-left: 0;
        border-bottom: 0;
      }

      .icon {
        margin-right: 4px;
      }
    }
  }
</style>
